<template>
  <div class="register">
	<view class="title">
		<view>{{$t('register.reg')}}</view>
		<view class="describe">Welcome to ChatAi</view>
	</view>

    <div class="loginbox">
		<view class="tx"></view>
		<view class="forms">
			<el-form :model="ruleForm" :rules="rules" ref="ruleForm" class="demo-ruleForm">
				<el-form-item prop="email" >
					<el-input type="email" v-model="ruleForm.email" :placeholder="$t('register.email')"></el-input>
				</el-form-item>
				<el-form-item prop="sms" class="sms">
				  <el-input v-model="ruleForm.sms" :placeholder="$t('register.verifyCode')" >
					<el-button v-show="show" slot="append" ref="popups" @click="CAptcha()" class="yzm" >{{$t('comm.getV')}}</el-button>
					<el-button v-show="!show" slot="append" ref="popups" style="margin: 0; text-align: center">{{ count }}</el-button>
				  </el-input>
				  <!-- <span class="hint" v-if="active === 'email'">Please check the verification code in the inbox or spam</span> -->
				</el-form-item>
				<el-form-item prop="login_password">
				  <el-input :placeholder="$t('register.pwd')" v-model="ruleForm.login_password" show-password></el-input>
				</el-form-item>
				<el-form-item>
				  <el-input :placeholder="$t('register.invite')" v-model="ruleForm.inviter_code" :readonly="mdf === 'f' ? true : false"></el-input>
				</el-form-item>
				<el-form-item>
				  <el-button type="primary" class="submit" @click="submitForm('ruleForm')">{{$t('register.confirm')}}</el-button>
				  <!-- <div class="google">
				  	<div id="signInDiv" class="google-button"></div>
				  </div> -->
				</el-form-item>
				<el-form-item>
				  <router-link :to="{ path: '/pages/login', query: { invite: ruleForm.inviter_code } }">
					<span class="fr link">{{$t('register.login')}}</span>
				  </router-link>
				</el-form-item>
			</el-form>
			<!-- <view class="footerFont">
				{{$t('register.tip1')}}<strong>12-1000 </strong>{{$t('register.tip2')}}.
			</view> -->
		</view>
    </div>
	
	<div class="g-recaptcha" id="g-recaptcha" style="z-index: 999;position: absolute;"></div>
  </div>
</template>

<script>
import generateID from '@/utils/generateID'
import { setToken } from '@/utils/auth'
import md5 from 'js-md5'
import regionData from '../static/json/region.json'
import cookie from 'js-cookie'

export default {
	name: 'register',
	data() {
		var validatePass = (rule, value, callback) => {
			if (value) {
				let z_reg = /((?=.*[a-z])(?=.*\d)|(?=[a-z])(?=.*[#@!~%^&*])|(?=.*\d)(?=.*[#@!~%^&*]))[a-z\d#@!~%^&*]{6,12}/i
				if (z_reg.test(value)) {
				  callback()
				} else {
				  callback(this.$t('resetPwd.pwdVail'))
				}
			}
		}
		return {
			ruleForm: {
				username: '',
				sms: '',
				login_password: null,
				inviter_code: ''
			},
			region: '',
			regionList: regionData,
			rules: {
				username: [
					{
						required: true,
						message: this.$t('register.valid.email'),
						trigger: 'blur'
					}
				],
				sms: [
					{
						required: true,
						message: this.$t('register.valid.verifyCode'),
						trigger: 'blur'
					}
				],
				login_password: [
					{
						required: true,
						message: this.$t('register.valid.pwd'),
						trigger: 'blur'
					},
					{ required: true, validator: validatePass , trigger: "blur" }
				]
			},
			captchaPoup: null,
			timer: null,
			show: true,
			count: '',
			active: 'email',
			mdf: 't'
		}
	},

  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let ruleFormNew = {}
			ruleFormNew = {
			email: this.ruleForm.email,
			sms: this.ruleForm.sms,
			login_password: md5(this.ruleForm.login_password).toUpperCase(),
			inviter_code: this.ruleForm.inviter_code && this.ruleForm.inviter_code != '' ? this.ruleForm.inviter_code : undefined
			}
		  this.$api.register.saveEmail(ruleFormNew).then((res) => {
		    if (res.code == '200') {
		      const that = this
		      this.$message({
		        message: res.msg,
		        type: 'success',
		        onClose: () => {
		  		that.$router.push({ path: '/pages/login' })
		        }
		      })
		    } else {
		      this.$message.error(res.msg)
		    }
		  })
        } else {
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
	
	// google login
	async callbackLogin(response) {
		const accessToken = response.credential
		const params = {
			input_token: accessToken,
			inviter_code: this.ruleForm.inviter_code,
			login_type: 'g'
		}
		this.$api.login.registerFacebook(params).then((res) => {
			if (res.code == '200') {
				let data = JSON.parse(res.data)
				setToken(data.token)
				localStorage.setItem('user', res.data)
				this.$router.push('/pages/home/index')
				//this.$router.push('/')
			}
		})
	},
    /**
     * Countdown for obtaining verification code
     */
    countDown() {
      const TIME_COUNT = 60
      if (!this.timer) {
        this.count = TIME_COUNT
        this.show = false
        this.timer = setInterval(() => {
          if (this.count > 0 && this.count <= TIME_COUNT) {
            this.count--
          } else {
            this.show = true
            clearInterval(this.timer)
            this.timer = null
          }
        }, 1000)
      }
    },
    /**
     * Obtain the email verification code
     */
    getEmailCode(validate) {
      // this.$api.register.getEmailCode()
      let jsonObj = {
        email: this.ruleForm.email,
        //NECaptchaValidate: validate,
		recaptchaToken:validate,
		sendType: 1
      }
      this.$api.register.getEmailCode(jsonObj).then((res) => {
		if (res.code == '200'){
			this.countDown();
		}else{
			if(res.hasOwnProperty('errorMsg')){
				this.$message.error(res.errorMsg);
			}else{
				this.$message.error(res.msg);
			}
		}
      })
    },
	CAptcha(){
		if(this.ruleForm.email===''||this.ruleForm.email===undefined){
			this.$message.error(this.$t('register.valid.email'))
			return false;
		}
		let that = this
		grecaptcha.render('g-recaptcha', {
		  'sitekey' : '6LfjFxknAAAAAGSCg3Fuj_x-DsXCtWUZms4n5tdT',
		  'callback' : function(token){
			  that.getEmailCode(token);
			  //close
			  document.getElementById('g-recaptcha').innerHTML='';
			},
		  'theme' : 'light'
		});
	},
    tabs(val) {
      this.active = val
      this.$refs['ruleForm'].clearValidate()
    },
    initClient() {
		// this.client = google.accounts.id.initialize({
		// 	client_id: '139543481401-e14uo74q4572khfq5jijv9ur3np0jt9k.apps.googleusercontent.com',
		// 	callback: (response) => this.callbackLogin(response)
		// })
    }
  },
  mounted() {
	 // google login
	 const googleBtnConfigs = {
		theme: 'outline',
		size: 'large',
		shape: 'pill',
		text: 'login_with',
		width: '50',
		locale: 'en'
	 }
	 google.accounts.id.prompt()
	 google.accounts.id.renderButton(document.getElementById('signInDiv'), googleBtnConfigs)
  },
  created() {
	const query = this.$route.query
	this.ruleForm.inviter_code = query.invite ? query.invite : ''
	if(query.l&&query.l==='ZH'){
		this.$i18n.locale = 'ZH'
		cookie.set("lang",'ZH')
	}
	this.initClient()
	/*
	else{
		this.$i18n.locale = 'EN'
		cookie.set("lang",'EN')
	}*/
  }
}
</script>
<style lang="scss">
.register {
	font-family: 'Gilroy';
	position: relative;
	min-height: 1400rpx;
	height: 100%;
    background:url('../static/images/login/bg_s.png') no-repeat center top;
	background-size:100%;
	/deep/ .title {
		width: 100%;
		padding-top:26rpx;
		font:400 36rpx/36rpx Arial;
		color: #fff;
		text-align: center;
		.describe {
			padding:50rpx 26rpx;
			font:400 60rpx/60rpx Arial;
			text-align: center;
		}
	}
	
	.loginbox {
		background-color: #fff;
		padding:60rpx 40rpx 10rpx 80rpx;
		position: absolute;
		// top:200rpx;
		// bottom: 0;
		width:90%;
		margin:140rpx 0rpx 0rpx 40rpx;
		border-radius: 20px;
		// height: calc(100% - 450rpx);
		box-sizing: border-box;
		.tx{
			width:120rpx;
			height:120rpx;
			background:url('../static/images/login/user.png') no-repeat center top;
			background-size:100%;
			position: relative;
			top: -58px;
			margin: 0 auto;
		}
		h4 {
			font: 500 56rpx/150rpx Arial;
			text-align: center;
		}
		.login-tabs {
			display: flex;
			width: 100%;
			height: 96rpx;
			border: 1px solid #ccc;
			border-radius: 48rpx;
			margin-bottom: 6rpx;
			.item {
				flex: 1;
				width: 100%;
				height: 84rpx;
				line-height: 84rpx;
				margin: 6rpx;
				text-align: center;
				font-size: 32rpx;
				font-weight: 500;
				color: #666;
				cursor: pointer;
				&.active {
					color: #8286cf;
					border-radius: 48rpx;
					background-color: #e6e7fc;
				}
			}
		}
		
		.forms {
			margin-top:10rpx;
			.el-form-item {
			    margin-bottom: 66rpx;
			}
			.link {
				color:rgba(51, 51, 51, 1);
				font: 400 24rpx/60rpx Arial;
			}
			.submit {
				margin-top:12rpx;
				width: 100%;
				height:100rpx !important;
				line-height:70rpx !important;
				font-size: 32rpx;
				font-weight:bold;
				color:rgba(255, 255, 255, 1);
                background: #6D50DF !important;
				border-radius: 25px;
				border:0;
				box-sizing: border-box;
			}
			/deep/ .username {
				position: relative;
				.el-input__inner {
					padding-left: 100rpx;
				}
				.el-input__suffix {
					position: absolute;
					left: 30rpx;
					right: auto;
					line-height: 96rpx;
					color: #999;
				}
			}
			.sms {
				position: relative;
				border-radius: 46rpx !important;
				background: #FFFFFF !important;
				border: 2rpx solid #D2CAFF !important;
				.hint {
					position: absolute;
					left: 0;
					bottom: -30rpx;
					// display: inline-block;
					font-size: 20rpx;
					color: #f56c6c;
					z-index: 999;
					height: 40rpx;
					line-height: 20rpx;
					
				}
				.el-form-item__error {
					width: 100%;
					z-index: 9999;
					background-color: #fff;
				}
			}
			/deep/ .el-input-group__append {
			  padding: 0 14rpx;
			  border:none  !important;
			  background:rgba(255, 255, 255, 0.1)  !important;
			  .el-button {
				  height: 70rpx;
				  border-radius:2rpx;
				  border: 0px solid transparent !important;
				  background-color:#FFF !important;
			  }
			  .yzm{
				  height:52rpx;
				  line-height:8rpx;
				  border-radius:6rpx;
				  margin:5rpx 5rpx 0 0;
				  font-size:24rpx;
				  font-weight: bold;
				  color:#6D50DF;
				  background:rgba(255, 255, 255, 0.1)  !important;
			  }
			}
		}
	}
}
#g-recaptcha {
	width:100%;
	div{
		width: 304px;
		height: 78px;
		margin: 135px auto;
   }
}
#g-recaptcha {
	width:100%;
	div{
		width: 304px;
		height: 78px;
		margin: 135px auto;
   }
}
.footerFont{
			//position: absolute;
			width:80%;
			margin:260rpx auto 0 auto;
			text-align: center;
			font-size:32rpx;
			line-height:60rpx;
			strong{
				font-size:44rpx;
			}
		}
// #rc-anchor-container{
// 	background-color: red !important;
// }
.google {
	margin-top: 3rem;
	text-align: center;
	.google-button {
		display: inline-block;
		text-align: center;
		width:384rpx;
		height:80rpx;
	}
	#signInDiv {
		iframe {
			margin: 0 !important;
			left: calc(50% - 105px) !important;
		}
	}
	
}
</style>
